package com.xiang.reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiang.reggie.common.Result;
import com.xiang.reggie.entity.User;
import com.xiang.reggie.service.UserService;
import com.xiang.reggie.util.SMSUtils;
import com.xiang.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 半山居雾
 * @date 2022/12/17 20:52
 */

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信验证码
     *
     * @param user    用户
     * @param session 会话
     * @return {@code Result<String>}
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();
//        String phone = map.get("phone");

        if ((phone != null)) {
            //生成随机的四位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}", code);

            //调用阿里云提供的短信服务api完成发送短信
//            SMSUtils.sendMessage("瑞吉外卖",phone,code);

            //需要将生成的验证码保存到session
//            session.setAttribute(phone, code);

        //优化：将系统生成的验证码存储到redis
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            return Result.success("手机验证码短信发送成功");
        }


        return Result.error("短信发送失败");
    }

    /**
     * 登录
     *
     * @param map     地图
     * @param session 会话
     * @return {@code Result<User>}
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody Map map, HttpSession session) {
        log.info(map.toString());

        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //从session中获取保存的验证码
//        Object codeInSession = session.getAttribute(phone);

        //优化：从redis中获取系统生成的验证码
        String codeInSession = (String) redisTemplate.opsForValue().get(phone);

        //比对验证码
        if (codeInSession != null && codeInSession.equals(code)) {
            //比对成功，登录成功
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);

            User user = userService.getOne(queryWrapper);
            if (user == null) {
                //判断当前手机号的用户是否为新用户，如果是就自动完成注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //设置操作限制条件
            session.setAttribute("user", user.getId());

            //删除redis中缓存的验证码，防止雪崩。。。
            redisTemplate.delete(phone);

            //返回给浏览器保存用户信息
            return Result.success(user);
        }
        return Result.error("登录失败");
    }


    /**
     * 注销
     *
     * @param session 会话
     * @return {@code Result<String>}
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpSession session) {
        session.removeAttribute("user");
        return Result.success("退出成功");
    }

}
